/*******************************************************************************
 * Copyright 2012 Thomas Letsch
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *******************************************************************************/
package com.googlecode.javaeeutils.jpa.manager;

import java.util.List;
import java.util.Stack;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import org.apache.commons.lang.reflect.FieldUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.googlecode.javaeeutils.jpa.PersistentEntity;

public class EntityManagerHelper {

    private static Logger log = LoggerFactory.getLogger(EntityManagerHelper.class);

    private static final ThreadLocal<Stack<EntityManager>> THREAD_LOCAL = new ThreadLocal<Stack<EntityManager>>();

    public static boolean isInitialized() {
        return (THREAD_LOCAL.get() != null) && (THREAD_LOCAL.get().lastElement() != null);
    }

    public static void put(EntityManager entityManager) {
        if (THREAD_LOCAL.get() == null) {
            THREAD_LOCAL.set(new Stack<EntityManager>());
        }
        THREAD_LOCAL.get().push(entityManager);
    }

    public static EntityManager get() {
        return THREAD_LOCAL.get().lastElement();
    }

    public static void reset() {
        THREAD_LOCAL.get().pop();
        if (THREAD_LOCAL.get().isEmpty()) {
            THREAD_LOCAL.remove();
        }
    }

    public static <ENTITY extends PersistentEntity> ENTITY findBy(Class<ENTITY> clazz, ENTITY entity, String... keys) {
        String query = "SELECT e FROM " + clazz.getSimpleName() + " e WHERE (1 = 1)";
        for (String key : keys) {
            query = query + " AND " + key + " = :" + key;
        }
        TypedQuery<ENTITY> jpaQuery = get().createQuery(query, clazz);
        for (String key : keys) {
            try {
                jpaQuery.setParameter(key, FieldUtils.readField(entity, key, true));
            } catch (IllegalAccessException e) {
                log.error("", e);
            }
        }
        List<ENTITY> resultList = jpaQuery.getResultList();
        if (resultList.size() > 1) {
            log.warn("findBy(clazz=" + clazz + ", entity=" + entity + ", keys=" + keys + ") is not unique! Returning " + resultList.get(0));
        }
        if (resultList.isEmpty()) {
            return null;
        }
        return resultList.get(0);
    }

}
